#!/bin/bash

help () {
    cat << EOF
Script for reporting device progress
resin-device-progress [options]

Options:
    -h, --help
        Display this help and exit.

    -c, --config-path CONFIG_PATH
        Use a non default config.json file.
        This argument is passed to balena-config-vars script.

    -p, --percentage PERCENTAGE
        Define progress in percentage

    -s, --state STATE
        String describing the current state.
EOF
}

# Parse arguments
while [ "$#" -gt "0" ]; do
    key=$1
    case $key in
        -h|--help)
            help
            exit 0
            ;;
        -c|--config-path)
            BALENA_VARS_ARGS="$BALENA_VARS_ARGS --config-path $2"
            shift
            ;;
        -p|--percentage)
            PERCENTAGE=$2
            shift
            ;;
        -s|--state)
            STATE=$2
            shift
            ;;
        *)
            echo "[WARNING] $0 : Argument '$1' unknown. Ignoring."
            ;;
    esac
    shift
done

# shellcheck disable=SC2086
source /usr/sbin/balena-config-vars $BALENA_VARS_ARGS

echo "-- $0 $PERCENTAGE $STATE $API_ENDPOINT $CONFIG_PATH" >> /var/log/provisioning-progress.log
if [ -z "$PERCENTAGE" ] || [ -z "$STATE" ] || [ -z "$API_ENDPOINT" ]; then
    echo "[ERROR] resin-device-progress : Needed variables not provided."
    exit 1
fi

if [ -z "$REGISTERED_AT" ]; then
    echo "[ERROR] resin-device-progress : Device registration not complete, provisioning progress cannot be reported."
    exit 1
fi

if [ -z "${UUID}" ]; then
    echo "[ERROR] resin-device-progress : Device UUID missing from config file, provisioning progress cannot be reported."
    exit 1
fi

# If the user api key exists we use it instead of the deviceApiKey as it means we haven't done the key exchange yet
_device_api_key=${PROVISIONING_API_KEY:-$DEVICE_API_KEY}

_outfile="/var/log/provisioning-progress-curl-$PERCENTAGE.log"
_errfile=$(mktemp)
if _status_code=$(\
        curl -s -X PATCH "${API_ENDPOINT}/v6/device(uuid='${UUID}')" \
            --show-error \
            -w "%{http_code}" \
            -L \
            --retry 3 \
            --header "Authorization: Bearer $_device_api_key" \
            -o "/var/log/provisioning-progress-curl-$PERCENTAGE.log" \
            --data-urlencode "provisioning_progress=$PERCENTAGE" \
            --data-urlencode "provisioning_state=$STATE" \
            --data-urlencode "status=configuring" 2> "${_errfile}"
    ); then
    case "${_status_code}" in
      2*) rm -f "${_errfile}"; exit 0;;
      *) echo "[WARN] [${_status_code}]: Request failed.";rm -f "${_errfile}"; exit 1;;
    esac
else
   echo "[WARN] $(cat "${_errfile}")"
   rm -f "${_errfile}"
   exit 1
fi
